package com.mozz.finally_work.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/*获取”时间线“数据，响应页面*/
@WebServlet(name = "TimelineServlet", value = "/TimelineServlet")
public class TimelineServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        /*验证用户是否登录*/
        if (userId.equals("")) {
            // TODO 验证
            response.sendRedirect("login.jsp");
            return;
        }
        /*获取用户的所有博客*/
        SqlSession session = MybatisUtils.getSession();
        BlogDao dao = session.getMapper(BlogDao.class);
        List<Blog> blogs = dao.queryAllBlogByUserId(userId);
        session.close();
        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writeValueAsString(blogs);
        /*存到request中*/
        request.setAttribute("blogs", value);
        /*请求转发*/
        request.getRequestDispatcher("timeline.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
